<?php session_start();

require_once("../config/tencent_config.php");
require_once("session.php");
require_once("utils.php");
require_once("tencent_api.php");

include_once('../../config.inc');
include_once(ROOT.'/database/open_api.php');

function tencent_callback()
{
	$_SESSION['callback_count'] ++;
	
	if ($_REQUEST['state'] == $_SESSION['state'])
	{
		$code = $_REQUEST["code"];
		$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
			. "client_id=" . APP_ID . "&redirect_uri=" . urlencode(CALLBACK)
			. "&client_secret=" . APP_KEY . "&code=" . $code;
		
		$response = get_url_contents($token_url);
		if (strpos($response, "callback") !== false)
		{
			$lpos = strpos($response, "(");
			$rpos = strrpos($response, ")");
			$response  = substr($response, $lpos + 1, $rpos - $lpos -1);
			$msg = json_decode($response);
			if (isset($msg->error))
			{
				echo "<h3>error:</h3>" . $msg->error;
				echo "<h3>msg  :</h3>" . $msg->error_description;
				exit;
			}
		}
		
		$params = array();
		parse_str($response, $params);
		
		$access_token = $params["access_token"];
		
		$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $access_token;

    $str  = get_url_contents($graph_url);
    if (strpos($str, "callback") !== false)
    {
        $lpos = strpos($str, "(");
        $rpos = strrpos($str, ")");
        $str  = substr($str, $lpos + 1, $rpos - $lpos -1);
    }

    $user = json_decode($str);
    if (isset($user->error))
    {
        echo "<h3>error:</h3>" . $user->error;
        echo "<h3>msg  :</h3>" . $user->error_description;
        exit;
    }
    
    $_SESSION["openid"] = $openid = $user->openid;
    $_SESSION["access_token"] = $access_token;
    
    $_SESSION["user_type"] = 2;
		$_SESSION["tencent_username"] = tencent_get_username($openid, $access_token);
		
		open_login(2, $openid, $access_token, "", $_SESSION["tencent_username"], "");
	}
	else 
	{
		echo("The state does not match. You may be a victim of CSRF.");
	}
}

// debug
// print_r($_REQUEST);

tencent_callback();

// debug
// print_r($_SESSION);

echo "<script>opener.location.reload();window.close();</script>";
?>